package com.winai.launcher.view;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.GridLayoutManager;

import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.ks.projectbasictools.utils.ToastUtil;
import com.winai.launcher.R;
import com.winai.launcher.base.BaseActivity;
import com.winai.launcher.base.BaseRecAdapter;
import com.winai.launcher.base.BaseRecViewHolder;
import com.winai.launcher.base.db.DB_Common;
import com.winai.launcher.bean.MenuBean;
import com.winai.launcher.constant.Constant;
import com.winai.launcher.constant.MainRouter;
import com.winai.launcher.manager.BehaviorStatisticsManager;
import com.winai.launcher.override.CountTimer;
import com.winai.launcher.utils.AppCollectUtil;
import com.winai.launcher.utils.BaseUtils;
import com.winai.launcher.utils.MathUtils;
import com.winai.launcher.utils.OpenAppUtils;
import com.winai.launcher.view.set.SetActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 作者：康少
 * 时间：2019/11/13
 * 描述：主菜单
 */
public class MainActivity extends BaseActivity {
    private Context mContext = this;

    @BindView(R.id.tv_debug)
    TextView tvDebug;
    @BindView(R.id.main_line)
    View mLine;
    @BindView(R.id.cl)
    ConstraintLayout cl;
    @BindView(R.id.recyclerView)
    LRecyclerView recyclerView;

    private List<MenuBean> menuBeanList = new ArrayList<>();
    private MainMenuAdapter mainMenuAdapter;
    private UserInfoReceiver userInfoReceiver;
    private boolean isShowTrain = false; //false 为普通用户隐藏销售培训，true 显示销售培训

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        start();
    }

    private void start() {
        initObject();
        initView();
        initData();
    }

    @SuppressLint("SetTextI18n")
    private void initView() {
        /*获取状态栏高度，不让状态栏背景与状态栏重合*/
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            ConstraintLayout.LayoutParams layoutParams = new ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
//            layoutParams.setMargins(0, StatusBarUtil.getStatusBarHeight(mContext), 0, 0);
//            cl.setLayoutParams(layoutParams);
//        }
//        if (isDebug(mContext)) {
        tvDebug.setVisibility(View.GONE);
        tvDebug.setText("DEBUG：" + BaseUtils.getLauncherVersion(mContext));
//        } else {
//            tvDebug.setVisibility(View.GONE);
//        }
    }

    private void initData() {
        DB_Common dbCommon = new DB_Common(mContext);
        String st = dbCommon.get("isShowTrain");
        this.isShowTrain = !TextUtils.isEmpty(st) && (st.equals("true"));
        menuBeanList.clear();
        menuBeanList.add(new MenuBean(
                7
                , "健康调养"
                , R.mipmap.icon_menu_search_illness
        ));
        menuBeanList.add(new MenuBean(
                4
                , "穴位查找"
                , R.mipmap.icon_menu_search_acupoint
        ));
        menuBeanList.add(new MenuBean(
                1
                , "调养须知"
                , R.mipmap.icon_menu_needknow
        ));
        menuBeanList.add(new MenuBean(
                13
                , "产品问答"
                , R.mipmap.icon_menu_answer
        ));
        menuBeanList.add(new MenuBean(
                2
                , "中医课程"
                , R.mipmap.icon_menu_class
        ));
        menuBeanList.add(new MenuBean(
                12
                , "趣味养生"
                , R.mipmap.icon_menu_funlive
        ));
        menuBeanList.add(new MenuBean(
                3
                , "名师直播"
                , R.mipmap.icon_menu_healthlive
        ));
        if (this.isShowTrain) {
            menuBeanList.add(new MenuBean(
                    8
                    , "销售培训"
                    , R.mipmap.icon_menu_video
            ));
        }
        menuBeanList.add(new MenuBean(
                6
                , "产品中心"
                , R.mipmap.icon_menu_project
        ));
        menuBeanList.add(new MenuBean(
                9
                , "QQ音乐"
                , R.mipmap.icon_menu_qqmusic
        ));
        menuBeanList.add(new MenuBean(
                14
                , "爱奇艺"
                , R.mipmap.icon_menu_iqiyi
        ));
        menuBeanList.add(new MenuBean(
                17
                , "日历"
                , R.mipmap.icon_menu_calendar
        ));
        menuBeanList.add(new MenuBean(
                15
                , "时钟"
                , R.mipmap.icon_menu_clock
        ));
        menuBeanList.add(new MenuBean(
                16
                , "闹钟"
                , R.mipmap.icon_menu_alarm
        ));
        menuBeanList.add(new MenuBean(
                11
                , "设置中心"
                , R.mipmap.icon_menu_set
        ));
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                mainMenuAdapter.refreshData(menuBeanList);
            }
        });
    }

    private void initObject() {
        mainMenuAdapter = new MainMenuAdapter();
        LRecyclerViewAdapter lRecyclerViewAdapter = new LRecyclerViewAdapter(mainMenuAdapter);
        recyclerView.setLayoutManager(new GridLayoutManager(mContext, 4));
        recyclerView.setAdapter(lRecyclerViewAdapter);
        recyclerView.setLoadMoreEnabled(false);
        recyclerView.setPullRefreshEnabled(false);
        recyclerView.setLScrollListener(new LRecyclerView.LScrollListener() {
            @Override
            public void onScrollUp() {

            }

            @Override
            public void onScrollDown() {

            }

            @Override
            public void onScrolled(int distanceX, int distanceY) {
                //计算比例，504是滑到底部的最大值得到的
                float proportion = (float) MathUtils.divide(distanceY, 504, 8);

                //计算滚动条宽度
                int transMaxRange = ((ViewGroup) mLine.getParent()).getHeight() - mLine.getHeight();
                //设置滚动条移动
                mLine.setTranslationY(transMaxRange * proportion);
            }

            @Override
            public void onScrollStateChanged(int state) {

            }
        });

        userInfoReceiver = new UserInfoReceiver();
        userInfoReceiver.register();
    }

    public boolean isDebug(Context context) {
        return context.getApplicationInfo() != null &&
                (context.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
    }

    @OnClick({R.id.iv_home, R.id.tv_vip, R.id.tv_collect, R.id.tv_history})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_home:
                //模拟HOME
                Intent intent = new Intent(Intent.ACTION_MAIN);
//                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.addCategory(Intent.CATEGORY_HOME);
                mContext.startActivity(intent);
                break;
            case R.id.tv_vip:
                OpenAppUtils.startIntentPath(mContext, MainRouter.PATH_USER_VIP, ".开通会员@");
                break;
            case R.id.tv_collect:
                OpenAppUtils.startIntentPath(mContext, MainRouter.PATH_USER_MY_COLLECT, ".我的收藏@");
                break;
            case R.id.tv_history:
                OpenAppUtils.startIntentPath(mContext, MainRouter.PATH_USER_MY_HISTORY, ".历史记录@");
                break;
        }
    }

    private class MainMenuAdapter extends BaseRecAdapter<MenuBean, MainMenuAdapter.ViewHolder> {
        @Override
        public void onHolder(ViewHolder holder, MenuBean menuBean, int position) {
            TextView textView = holder.getView(R.id.tv_item);
            textView.setText(menuBean.getName());

            Drawable drawable = getResources().getDrawable(menuBean.getMipmapId());
            /// 这一步必须要做,否则不会显示.
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            textView.setCompoundDrawables(null, drawable, null, null);

            textView.setOnClickListener(v -> {
                switch (menuBean.getId()) {
                    case 1://调养须知
                        OpenAppUtils.startIntentPath(mContext, MainRouter.PATH_FORUM_NOTICE, ".调养须知@");
                        BehaviorStatisticsManager.getInstance(mContext).goInPage("调养须知");
                        break;
                    case 2://中医课程
                        OpenAppUtils.startIntentPath(mContext, MainRouter.PATH_AUDIO_VIDEO, ".中医课程@");
                        BehaviorStatisticsManager.getInstance(mContext).goInPage("中医课程");
                        break;
                    case 3://名师直播
                        OpenAppUtils.startIntentPath(mContext, MainRouter.PATH_AUDIO_LIVE, ".名师直播@");
                        BehaviorStatisticsManager.getInstance(mContext).goInPage("名师直播");
                        break;
                    case 4://穴位查找
                        OpenAppUtils.startIntentPath(mContext, MainRouter.PATH_MEDICINE_ACUPOINT, ".穴位查找@");
                        BehaviorStatisticsManager.getInstance(mContext).goInPage("穴位查找");
                        break;
                    case 5://养生音乐
                        OpenAppUtils.startIntentPath(mContext, MainRouter.PATH_AUDIO_MUSIC, ".养生音乐@");
                        break;
                    case 6://产品中心
                        OpenAppUtils.startIntentPath(mContext, MainRouter.PATH_FORUM_PRODUCT, ".产品中心@");
                        BehaviorStatisticsManager.getInstance(mContext).goInPage("产品中心");
                        break;
                    case 7://健康调养
                        OpenAppUtils.startIntentPath(mContext, MainRouter.PATH_MEDICINE_DISEASE, ".健康调养@");
                        BehaviorStatisticsManager.getInstance(mContext).goInPage("健康调养");
                        break;
                    case 8://销售培训
                        OpenAppUtils.startIntentPath(mContext, MainRouter.PATH_AUDIO_VIDEO3, ".销售培训@");
                        BehaviorStatisticsManager.getInstance(mContext).goInPage("销售培训");
                        break;
                    case 9://QQ音乐
                        OpenAppUtils.launchAPK3(mContext, "com.tencent.qqmusiccar", "QQ音乐");
                        break;
                    case 10://喜马拉雅
                        ToastUtil.show(mContext, "敬请期待…");
//                        OpenAppUtils.launchAPK3(mContext, "com.ximalaya.ting.android","喜马拉雅");
                        break;
                    case 11://设置中心
                        startActivity(new Intent(mContext, SetActivity.class));
                        break;
                    case 12://趣味养生
                        OpenAppUtils.startIntentPath(mContext, MainRouter.PATH_AUDIO_INTEREST_VIDEO, ".趣味养生@");
                        BehaviorStatisticsManager.getInstance(mContext).goInPage("趣味养生");
                        break;
                    case 13://产品问答
                        OpenAppUtils.startIntentPath(mContext, MainRouter.PATH_FORUM_PRODUCT_QA_HOME, ".产品问答@");
                        BehaviorStatisticsManager.getInstance(mContext).goInPage("产品问答");
                        break;
                    case 14://爱奇艺
                        OpenAppUtils.launchAPK3(mContext, "com.qiyi.video.speaker", "爱奇艺");
                        break;
                    case 15://时钟
                        OpenAppUtils.startIntentPath(mContext, MainRouter.PATH_SETTING_CLOCK, ".时钟@");
                        break;
                    case 16://闹钟
                        OpenAppUtils.startIntentPath(mContext, MainRouter.PATH_SETTING_ALARM, ".闹钟@");
                        break;
                    case 17://日历
                        OpenAppUtils.startIntentPath(mContext, MainRouter.PATH_SETTING_CALENDAR, ".日历@");
                        break;
                }
            });
        }

        @Override
        public ViewHolder onCreateHolder() {
            return new ViewHolder(getViewByRes(R.layout.item_menu));
        }

        private class ViewHolder extends BaseRecViewHolder {
            ViewHolder(View itemView) {
                super(itemView);
            }
        }
    }

    /**
     * @author kangshao
     * @date 4/26/21
     * @desc 用户信息广播-隐藏或显示销售培训
     * 　　　　　　　　┏┓　　　┏┓
     * 　　　　　　　┏┛┻━━━┛┻┓
     * 　　　　　　　┃　　　　　　  ┃
     * 　　　　　　　┃　　　━ 　　　┃
     * 　　　　　　　┃　＞　　　＜　┃
     * 　　　　　　　┃　　　　　　　┃
     * 　　　　　　　┃ ...　⌒　... ┃
     * 　　　　　　　┃　　　　　　　┃
     * 　　　　　　　 ┗━┓　　　 ┏━┛
     * 　　　　　　　　　┃　　　┃　Code is far away from bug with the animal protecting
     * 　　　　　　　　　┃　　　┃   神兽保佑,代码无bug
     * 　　　　　　　　　┃　　　┃
     * 　　　　　　　　　┃　　　┃
     * 　　　　　　　　　┃　　　┃
     * 　　　　　　　　　┃　　　┃
     * 　　　　　　　　　┃　　　┗━━━┓
     * 　　　　　　　　　┃　　　　　　　┣┓
     * 　　　　　　　　　┃　　　　　　　┏┛
     * 　　　　　　　　　┗┓┓┏━┳┓┏┛
     * 　　　　　　　　　　┃┫┫　┃┫┫
     * 　　　　　　　　　　┗┻┛　┗┻┛
     */
    private class UserInfoReceiver extends BroadcastReceiver {

        public void register() {
            IntentFilter filter = new IntentFilter();
            filter.addAction(Constant.ACTION_USER_INFO_Launcher);
            mContext.registerReceiver(this, filter);
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction() != null && intent.getAction().equals(Constant.ACTION_USER_INFO_Launcher)) {
                initData();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        CountTimer.restart(mContext);
        BehaviorStatisticsManager.getInstance(mContext).goInMainPage();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            unregisterReceiver(userInfoReceiver);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
    }
}
